package com.yungu.swift.order.processor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.assets.driver.model.dto.DriverCommissionConfigDto;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.order.consts.Constants;
import com.yungu.swift.order.model.dto.OrderDto;
import com.yungu.swift.order.model.dto.OrderFareDto;
import com.yungu.swift.order.model.dto.OrderRechargeDto;
import com.yungu.swift.order.model.param.CrosstownAssignOrderParam;
import com.yungu.swift.order.model.vo.JsonOrderDetailVo;
import com.yungu.swift.order.model.vo.PayVo;
import com.yungu.swift.order.service.OrderAssignService;
import com.yungu.swift.order.service.OrderFareService;
import com.yungu.swift.order.service.OrderRechargeService;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by cuixiuyin on 2018/5/8.
 * 订单业务处理器
 */
@Component
public class OrderProcessor implements PayProcessor {

    private static final Logger logger = LoggerFactory.getLogger(OrderProcessor.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderFareService orderFareService;
    @Autowired
    private OrderRechargeService orderRechargeService;
    @Autowired
    private OrderAssignService orderAssignService;
    @Autowired
    private CrosstownOrderProcessor crosstownOrderProcessor;

    @Reference
    private DriverService driverService;

    @Override
    public void process(PayVo payVo) {
        if (payVo.getPayPurpose() == OrderConstant.PAY_PURPOSE_CHARGE_FARE) {
            OrderDto updateOrderDto = new OrderDto();
            updateOrderDto.setUuid(payVo.getOrderUuid());

            //更新订单状态
            Integer subStatus = payVo.getOrderDto().getSubStatus();
            Integer mainStatus;

            logger.info("------------【支付】回调更新订单相关信息Start：" + payVo.getOrderDto().getUuid() + "------------------------");
            //正常流程的单子
            if (OrderConstant.ORDER_STATUS_FARE_CONFIRM.equals(subStatus)) {
                subStatus = OrderConstant.ORDER_STATUS_COMPLETE;
                mainStatus = OrderConstant.ORDER_MAIN_STATUS_PAYED;
            } else {
                //[行程确定]乘客取消
                if (OrderConstant.ORDER_STATUS_PAY_CONFIRM_PASS_CANCEL.equals(subStatus)) {
                    subStatus = OrderConstant.ORDER_STATUS_PASS_CANCEL_CONFIRM_PAY;
                }
                //[行程确定]司机取消
                if (OrderConstant.ORDER_STATUS_PAY_CONFIRM_DRI_CANCEL.equals(subStatus)) {
                    subStatus = OrderConstant.ORDER_STATUS_DRI_CANCEL_CONFIRM_PAY;
                }
                //[去接乘客]乘客取消
                if (OrderConstant.ORDER_STATUS_PAY_GO_PASS_CANCEL.equals(subStatus)) {
                    subStatus = OrderConstant.ORDER_STATUS_PASS_CANCEL_GO_PAY;
                }
                //[去接乘客]司机取消
                if (OrderConstant.ORDER_STATUS_PAY_GO_DRI_CANCEL.equals(subStatus)) {
                    subStatus = OrderConstant.ORDER_STATUS_DRI_CANCEL_GO_PAY;
                }
                //[到达上车地点]乘客取消
                if (OrderConstant.ORDER_STATUS_PAY_WAIT_PASS_CANCEL.equals(subStatus)) {
                    subStatus = OrderConstant.ORDER_STATUS_PASS_CANCEL_WAIT_PAY;
                }
                //[到达上车地点]司机取消
                if (OrderConstant.ORDER_STATUS_PAY_WAIT_DRI_CANCEL.equals(subStatus)) {
                    subStatus = OrderConstant.ORDER_STATUS_DRI_CANCEL_WAIT_PAY;
                }
                mainStatus = OrderConstant.ORDER_MAIN_STATUS_CANCEL;
            }

            //更新订单支付类型
            int orderPayType = 0;
            int orderFarePayType = 0;

            if (payVo.getActualFare().compareTo(BigDecimal.ZERO) == 0) {
                if (payVo.getActualDeductible().compareTo(BigDecimal.ZERO) == 1) {
                    //优惠券完全抵扣
                    orderPayType = OrderConstant.PAY_TYPE_COUPON;
                } else {
                    //零元支付处理
                    orderPayType = OrderConstant.PAY_TYPE_ZERO;
                }
            } else {
                //乘客余额支付/第三方支付
                if (payVo.getPaySide() == CommonConstant.PASSENGER
                        || payVo.getPaySide() == CommonConstant.PASSENGER_PULBIC
                        || payVo.getPaySide() == CommonConstant.PASSENGER_H5
                        || payVo.getPaySide() == CommonConstant.PASSENGER_APPLET) {
                    if (payVo.getPayType() == OrderConstant.PAY_TYPE_BALANCE) {
                        orderPayType = OrderConstant.PAY_TYPE_BALANCE;
                    } else {
                        orderPayType = payVo.getPayType();
                    }
                    orderFarePayType = payVo.getPayType();
                }
                //司机代付订单类型显示司机实际支付类型
                if (payVo.getPaySide() == CommonConstant.DRIVER) {
                    orderPayType = payVo.getPayType();
                    orderFarePayType = payVo.getPayType();
                }
            }
            //更新订单表
            updateOrderDto.setMainStatus(mainStatus);
            updateOrderDto.setSubStatus(subStatus);
            updateOrderDto.setPayPurpose(payVo.getPayPurpose());
            updateOrderDto.setPaySide(payVo.getPaySide());
            updateOrderDto.setPayType(orderPayType);
            Integer typeModule = payVo.getOrderDto().getTypeModule();
            if (typeModule == CommonConstant.BUSINESS_TYPE_POOL || typeModule == CommonConstant.BUSINESS_TYPE_PARCEL) {
                //先付费订单更新成 预约中 后付费订单更新成已完成
                if (OrderConstant.ORDER_PAY_PATTERN_FRONT.equals(payVo.getOrderDto().getPayPattern())) {
                    //如果订单等于扫码下单 则直接进入派单成功状态
                    if (payVo.getOrderDto().getSource() == OrderConstant.ORDER_SOURCE_SCAN_CODE) {
                        updateOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_WAIT_START);
                    } else {
                        updateOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_SUBING);
                    }
                } else {
                    updateOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_COMPLETED);
                }
            }
            updateOrderDto.setPayStatus(Constants.ORDER_PAY_STATUS_PAYED);
            updateOrderDto.setPayTime(new Date());
            updateOrderDto.setUpdateOn(new Date());
            orderService.edit(updateOrderDto);
            //更新订单价格表
            OrderFareDto updateOrderFareDto = new OrderFareDto();
            updateOrderFareDto.setUuid(payVo.getOrderFareDto().getUuid());
            updateOrderFareDto.setActualFare(payVo.getActualFare().doubleValue());
            updateOrderFareDto.setCouponFare(payVo.getActualDeductible().doubleValue());
            updateOrderFareDto.setPayType(orderFarePayType);
            updateOrderFareDto.setPayTime(new Date());
            updateOrderFareDto.setUpdateOn(new Date());
            orderFareService.edit(updateOrderFareDto);

            logger.info("--【支付】增加乘客订单数成功：" + payVo.getOrderDto().getUuid() + "--");

            //跨城订单支付完成 并且为先付费的订单 需要进行派单逻辑
            if (payVo.getOrderDto().getTypeModule() == CommonConstant.BUSINESS_TYPE_POOL || payVo.getOrderDto().getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
                if (OrderConstant.ORDER_PAY_PATTERN_FRONT.equals(payVo.getOrderDto().getPayPattern())) {
                    //如果是扫码下单 不需要处理派单信息
                    if (payVo.getOrderDto().getSource() == OrderConstant.ORDER_SOURCE_SCAN_CODE) {
                        logger.info("======先付费订单:扫码下单不需要处理派单=====");
                    } else {
                        logger.info("======先付费订单:跨城订单支付回调派单处理=====");
                        CrosstownAssignOrderParam crosstownAssignOrderParam = new CrosstownAssignOrderParam();
                        crosstownAssignOrderParam.setCurrentOrderUuid(payVo.getOrderDto().getUuid());
                        ResponseData<JsonOrderDetailVo> assignJoinOrderRS = orderAssignService.doAssignCrosstownOrderAuto(crosstownAssignOrderParam);
                        if (!assignJoinOrderRS.isSuccess()) {
                            logger.error(">>先付费订单:跨城订单支付回调派单处理异常：msg:{}", assignJoinOrderRS.getMsg());
                        } else {
                            logger.info("======先付费订单:跨城订单支付回调派单处理完成.======");
                        }
                    }

                } else {
                    OrderDto settleOrder = payVo.getOrderDto();
                    settleOrder.setPayType(orderPayType);
                    logger.info("=====后付费订单:跨城订单支付处理订单结算=====");
                    DriverCommissionConfigDto driverCommissionConfigDto = driverService.getDriverCommissionConfig(payVo.getDriverVo().getUuid()).getData();
                    if (driverCommissionConfigDto != null) {
                        logger.info("=====获取到司机单独的佣金配置=====:{}", JsonUtils.toJSONString(driverCommissionConfigDto));
                        payVo.setDriverCommissionConfigDto(driverCommissionConfigDto);
                    }
                    ResponseData<BigDecimal> calcuFareRsd = crosstownOrderProcessor.orderFareSettlement(payVo.getOrderDto());
                    if (!calcuFareRsd.isSuccess()) {
                        payVo.setOrderBalance(new BigDecimal(0));
                        //结算失败
                        logger.error("后付费付费订单ID{}:跨城订单支付回调结算处理异常:{}", payVo.getOrderUuid(), calcuFareRsd.getMsg());
                    } else {
                        //设置订单司机收入
                        payVo.setOrderBalance(calcuFareRsd.getData());
                        logger.info("=====后付费订单ID{}:跨城订单支付回调派结算处理完成.=====", payVo.getOrderUuid());
                        //校验乘客是否都已支付 若都支付 则更新主订单状态为已支付
                        boolean isComplete = crosstownOrderProcessor.verifyOrderStatus(OrderConstant.ORDER_JOIN_STATUS_COMPLETED, payVo.getOrderDto().getMainOrderUuid());
                        if (isComplete) {
                            logger.error("后付费付费订单ID{}:全部已支付，更新主状态信息成功", payVo.getOrderUuid());
                        }
                    }
                }
            }
        }

        if (payVo.getPayPurpose() == OrderConstant.PAY_PURPOSE_RECHARGE_ACCOUNT) {
            logger.info("【充值】回调更新订单相关信息开始：{}", payVo.getOrderUuid());
            //更新充值订单状态
            OrderRechargeDto updateOrderRechargeDto = new OrderRechargeDto();
            updateOrderRechargeDto.setUuid(payVo.getOrderUuid());
            updateOrderRechargeDto.setStatus(OrderRechargeDto.STATUS_PAID);
            orderRechargeService.edit(updateOrderRechargeDto);
            logger.info("【充值】回调更新订单相关信息完成：{}", payVo.getOrderUuid());
        }

        logger.info(payVo.getDescription() + "--处理订单逻辑完毕");
    }
}
